﻿<%@ page import="java.util.Date" %><%--
  Created by IntelliJ IDEA.
  User: bb
  Date: 2021/10/18
  Time: 13:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link href="jquery-easyui-1.7.0/themes/default/easyui.css" rel="stylesheet" type="text/css" />
    <link href="jquery-easyui-1.7.0/themes/icon.css" rel="stylesheet" type="text/css" />
    <link href="jquery-easyui-1.7.0/demo/demo.css" rel="stylesheet" type="text/css" />
    <script src="jquery-easyui-1.7.0/jquery.min.js" type="text/javascript"></script>
    <script src="jquery-easyui-1.7.0/jquery.easyui.min.js" type="text/javascript"></script>
    <script src="jquery-easyui-1.7.0/locale/easyui-lang-zh_CN.js" type="text/javascript"></script>
</head>
<body>
    <%--datagrid--%>
    <table id="datagrid_CreateOrder" class="easyui-datagrid"></table>
    <%--header--%>
    <div id="header" style="padding: 3px">
        客户名称：&nbsp;<input class="easyui-combobox" id="customerName" name="customerName" value="0" style="width: 115px"
                          data-options=" valueField:'id', textField:'userName', url:'userInfo/getValidUser' "/>&nbsp;&nbsp;
        订单金额：&nbsp;<input class="easyui-textbox" id="orderPrice" name="orderPrice" readonly="readonly" style="width: 115px"/>&nbsp;&nbsp;
        <br>
        订单日期：&nbsp;<input class="easyui-datebox" id="orderDate" name="orderDate" style="width: 115px" value="<%=new Date().toString()%>">&nbsp;&nbsp;
        订单状态：&nbsp;<select class="easyui-combobox" id="orderStatus" name="orderStatus" style="width: 115px">
                        <option value="未付款" selected>未付款</option>
                        <option value="已付款">已付款</option>
                        <option value="未发货">未发货</option>
                        <option value="已发货">已发货</option>
                        <option value="已完成">已完成</option>
                      </select>
    </div>
    <%--toolbar--%>
    <div id="toolbar_CreateOrder" style="padding: 2px 5px">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="addOrderDetail();">添加订单明细</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-save" plain="true" onclick="saveOrder();">保存订单</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" plain="true" onclick="deleteOrder();">删除订单明细</a>
    </div>

    <script>
        $(function (){
            $('#datagrid_CreateOrder').datagrid({
                rownumbers:true,
                singleSelect:false,
                fit:true,
                fitColumn:true,
                header:'#header',//为datagrid添加搜索栏
                toolbar:'#toolbar_CreateOrder',//为datagrid添加工具栏
                columns:[[{
                    title:'序号',
                    field:'',// ??
                    align:'center',
                    checkbox:true
                },{
                    field: 'pid',
                    title: '商品名称',
                    width:280,
                    editor:{
                        type:'combobox',
                        options:{
                            valueField:'id',
                            textField:'name',
                            url:'product/getOnSaleProduct',
                            onChange:function (newValue, oldValue){
                                var rows = $('#datagrid_CreateOrder').datagrid("getRows");
                                var orderPrice = 0;
                                for (var i = 0; i < rows.length; i++){ //遍历所有的行
                                    var pidEd = $('#datagrid_CreateOrder').datagrid('getEditor',{
                                        index:i,
                                        field:'pid'
                                    });
                                    var priceEd = $('#datagrid_CreateOrder').datagrid('getEditor',{
                                        index:i,
                                        field:'price'
                                    });
                                    var totalpriced = $('#datagrid_CreateOrder').datagrid('getEditor',{
                                        index:i,
                                        field:'totalprice'
                                    });
                                    var numEd = $('#datagrid_CreateOrder').datagrid('getEditor',{
                                        index:i,
                                        field:'num'
                                    });
                                    if (pidEd != null){
                                        var pid = $(pidEd.target).combobox('getValue');
                                        $.ajax({ //向后台发送ajax请求，根据s商品id获取商品单价
                                            type: 'POST',
                                            url: 'product/getPriceById',
                                            data:{
                                                pid:pid
                                            },
                                            success:function (result){ //成功之后的回调函数 后台返回的单价赋值给result
                                                $(priceEd.target).numberbox('setValue', result); //单价
                                                $(totalpriced.target).numberbox('setValue',result * $(numEd.target).numberbox('getValue')); //小计
                                                orderPrice = Number(orderPrice) + Number($(totalpriced.target).numberbox('getValue'));
                                            },
                                            dataType:'json',
                                            async:false
                                        });
                                    }
                                }
                                $("#orderPrice").textbox("setValue",orderPrice); //订单金额
                            }
                        }
                    }
                },{
                    field: 'price',
                    title: '单价',
                    width:80,
                    editor: {
                        type: "numberbox",
                        options: {
                            editable:false
                        }
                    }
                },{
                    field: 'num',
                    title: '数量',
                    width:80,
                    editor: {
                        type: 'numberbox',
                        options: {
                            onChange:function (newValue, oldValue){
                                var rows = $("#datagrid_CreateOrder").datagrid("getRows");
                                var orderPrice = 0;
                                for (var i =0; i < rows.length; i++){
                                    var priceEd = $('#datagrid_CreateOrder').datagrid('getEditor',{
                                        index: i,
                                        field: 'price'
                                    });
                                    var totalpriceEd = $("#datagrid_CreateOrder").datagrid('getEditor',{
                                        index:i,
                                        field:'totalprice'
                                    });
                                    var numEd = $('#datagrid_CreateOrder').datagrid('getEditor',{
                                        index:i,
                                        field:'num'
                                    });
                                    $(totalpriceEd.target).numberbox('setValue', $(priceEd.target).numberbox('getValue') * $(numEd.target).numberbox('getValue')); //小计 = 单价 * 数量
                                    //console.log($(priceEd.target).numberbox('getValue'))//调试
                                    orderPrice = Number(orderPrice) + Number($(totalpriceEd.target).numberbox("getValue"));//订单总价 = 每行小计 之和 （循环）
                                }
                                $("#orderPrice").textbox("setValue",orderPrice);
                            }
                        }
                    }
                },{
                    field: 'totalprice',
                    title: '小计',
                    width:80,
                    editor: {
                        type: "numberbox",
                        options: {
                            editable: false
                        }
                    }
                }]]
            })
        })
    </script><%--datagrid--%>
    <script>
        function addOrderDetail(){
            $('#datagrid_CreateOrder').datagrid('appendRow',{
                num:1,
                price:0,
                totalprice:0
            });
            var rows = $("#datagrid_CreateOrder").datagrid('getRows');
            //console.log(rows);//调试
            //使添加的行处于可编辑状态
            $('#datagrid_CreateOrder').datagrid('beginEdit',rows.length -1); //从尾部添加记录行
        }
        function deleteOrder(){
            var rows = $('#datagrid_CreateOrder').datagrid('getSelections');
            var len = rows.length;
            if (len > 0){
                //获取订单金额
                var orderPrice = $('#orderPrice').textbox('getValue');
                //遍历所选行，订单金额减去这些行的小计金额
                for (var i = 0; i < len; i++){
                    var index = $('#datagrid_CreateOrder').datagrid('getRowIndex', rows[i]);//获取当前遍历的行的下标
                    var temp = $('#datagrid_CreateOrder').datagrid('getEditor',{
                        index:index,
                        field:'totalprice'
                    }); //获取当前遍历的行的小计金额
                    orderPrice -= Number($(temp.target).numberbox('getValue'));
                    $('#datagrid_CreateOrder').datagrid('deleteRow', index);
                }
                $('#orderPrice').textbox('setValue', orderPrice);
            }else{
                $.messager.alert("提示", '请选择要删除的行', 'info');
            }
        }

        function create_endEdit() {
            var rows = $('#datagrid_CreateOrder').datagrid('getRows');
            var len = rows.length;
            for (var i = 0; i < len; i++){
                $('#datagrid_CreateOrder').datagrid('endEdit', i);
            }
        }   //取消datagrid控件的行编辑状态

        function saveOrder(){
            //获取订单客户
            var user = $('#customerName').combobox('getValue');
            if (user == 0){
                $.messager.alert("提示", '请选择客户名称', 'info');
            }else {
                /*var rows = $('#datagrid_CreateOrder').datagrid('getSelections');
                if ( rows.length ){*/
                    //console.log(rows.length)//调试
                    create_endEdit();   //取消datagrid控件的行编辑状态
                    //主表
                    var orderInfo =[];  //数组变量 用于存放订单主表数据
                    var orderTime = $('#orderDate').datebox('getValue');//获取订单日期
                    //console.log(orderTime)//调试
                    var status = $('#orderStatus').combobox('getValue');//获取订单状态
                    var orderPrice = $('#orderPrice').textbox("getValue");//获取订单金额
                    orderInfo.push({
                        status:status,
                        orderprice:orderPrice,
                        ordertime:orderTime,
                        uid:user
                    });
                    //副表
                    if ( $('#datagrid_CreateOrder').datagrid('getChanges').length ){
                        var inserted = $('#datagrid_CreateOrder').datagrid('getChanges', "inserted");//获取datagrid控件中插入的行
                        var effectRow = new Object();
                        //console.log(inserted.length)//调试
                        if (inserted.length){
                            effectRow["inserted"] = JSON.stringify(inserted);//等价于 effectRow.inserted = JSON.stringify(inserted);
                        }
                        effectRow["orderInfo"] = JSON.stringify(orderInfo);
                        //提交请求
                        $.post("order/commitOrder", effectRow, function (data){
                            if (data == 'success'){
                                $.messager.alert("提示",'创建订单成功！');
                                $('#datagrid_CreateOrder').datagrid('acceptChanges');
                                if ( $('#tabs').tabs('exists', '创建订单') ){
                                    $('#tabs').tabs('close', '创建订单');
                                    $('#tabs').tabs('add',{
                                        title:'创建订单',
                                        href:'createOrder.jsp',
                                        closable:true
                                    });
                                }
                                $('#datagrid_SearchOrder').datagrid('reload');
                            }else {
                                $.messager.alert("提示",'创建订单失败！');
                            }
                        });
                    }
                /*}else {
                    $.messager.alert("提示", '请勾选需要保存的订单！', 'info');
                }*/
            }
        }
    </script><%--toolbar--%>
</body>
</html>
